// src/context/ProductADContext.tsx
import React, { createContext, useState, useCallback } from 'react';
import {
    productADService,
    type ProductAd,
    type CreateProductAdInput
} from '../api/service/ProductADService';

// 定义广告上下文类型
interface ProductADContextType {
    ads: ProductAd[];
    loading: boolean;
    loadingCreate: boolean;
    loadingDelete: boolean;
    error: string | null;
    fetchAds: () => Promise<void>;
    createAd: (input: CreateProductAdInput) => Promise<boolean>;
    deleteAd: (id: string) => Promise<boolean>;
}

// 创建上下文
const ProductADContext = createContext<ProductADContextType | undefined>(undefined);

// Provider 组件
export const ProductADProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [ads, setAds] = useState<ProductAd[]>([]);
    const [loading, setLoading] = useState<boolean>(false);
    const [loadingCreate, setLoadingCreate] = useState<boolean>(false);
    const [loadingDelete, setLoadingDelete] = useState<boolean>(false);
    const [error, setError] = useState<string | null>(null);

    // 获取广告列表
    const fetchAds = useCallback(async () => {
        setLoading(true);
        setError(null);
        try {
            const result = await productADService.getProductAdList();
            setAds(result.advertisingList);
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '获取广告列表失败');
            console.error('获取广告列表失败:', err);
        } finally {
            setLoading(false);
        }
    }, []);

    // 创建广告
    const createAd = useCallback(async (input: CreateProductAdInput): Promise<boolean> => {
        setLoadingCreate(true);
        setError(null);
        try {
            const ad = await productADService.createProductAd(input);
            // 将新创建的广告添加到列表开头
            setAds(prev => [ad, ...prev]);
            return true;
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '创建广告失败');
            console.error('创建广告失败:', err);
            return false;
        } finally {
            setLoadingCreate(false);
        }
    }, []);

    // 删除广告
    const deleteAd = useCallback(async (id: string): Promise<boolean> => {
        setLoadingDelete(true);
        setError(null);
        try {
            const result = await productADService.deleteProductAd(id);
            if (result) {
                // 从广告列表中移除已删除的广告
                setAds(prev => prev.filter(ad => ad.id !== id));
            }
            return result;
        } catch (err: unknown) {
            const errorMessage = err instanceof Error ? err.message : String(err);
            setError(errorMessage || '删除广告失败');
            console.error('删除广告失败:', err);
            return false;
        } finally {
            setLoadingDelete(false);
        }
    }, []);


    return (
        <ProductADContext.Provider
            value={{
                ads,
                loading,
                loadingCreate,
                loadingDelete,
                error,
                fetchAds,
                createAd,
                deleteAd,
            }}
        >
            {children}
        </ProductADContext.Provider>
    );
};

export default ProductADContext;
